package cn.ujn.medicalbackend.controller;

import cn.ujn.medicalbackend.common.BaseResponse;
import cn.ujn.medicalbackend.common.ErrorCode;
import cn.ujn.medicalbackend.common.ResultUtils;
import cn.ujn.medicalbackend.domain.City;
import cn.ujn.medicalbackend.dto.CityQuery;
import cn.ujn.medicalbackend.exception.BusinessException;

import cn.ujn.medicalbackend.request.CityAddRequest;
import cn.ujn.medicalbackend.request.CityDeleteRequest;
import cn.ujn.medicalbackend.request.CityUpdateRequest;
import cn.ujn.medicalbackend.service.CityService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/city")
@CrossOrigin(origins = {"http://localhost:9092"})
public class CityController {
    @Autowired
    private CityService cityService;

    @GetMapping("/list/city")
    public BaseResponse<Page<City>> getcityListByPage(CityQuery cityQuery) {
        if (cityQuery== null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        City city = new City();
        BeanUtils.copyProperties(cityQuery, city);
        QueryWrapper<City> queryWrapper = new QueryWrapper<>(city);
        Page<City> page = new Page<>(cityQuery.getPageNum(), cityQuery.getPageSize());
        Page<City> tempPage = cityService.page(page, queryWrapper);
        Page<City> resultPage = cityService.cityPageTransfer(tempPage);
        return ResultUtils.success(resultPage);
    }
    @PostMapping("/add")
    public BaseResponse<Long> addCity(@RequestBody CityAddRequest cityAddRequest, HttpServletRequest request) {
        if (cityAddRequest== null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        long cityId =cityService.addCity(cityAddRequest, request);
        return ResultUtils.success(cityId);
    }

    @PostMapping("/update")
    private BaseResponse<Boolean> updateCity(@RequestBody CityUpdateRequest cityUpdateRequest, HttpServletRequest request) {

        if (cityUpdateRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        boolean result = cityService.updateCity(cityUpdateRequest,request);
        return ResultUtils.success(true);
    }

    @PostMapping("/delete")
    private BaseResponse<Boolean> deleteCity(@RequestBody CityDeleteRequest cityDeleteRequest, HttpServletRequest request) {
        if (cityDeleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result =  cityService.deleteCity(cityDeleteRequest, request);
        return ResultUtils.success(result);
    }
}
